package com.neusoft.hifly.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;

/**
 * SpringBoot 2.x 整合lettuce
 */
@Configuration
public class RedisConfig {

	@Bean
	public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory factory) {

		// RedisTemplate使用lettuce连接池配置
		factory.setShareNativeConnection(false);

		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(factory);

		// 序列化使用FastJson
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();

		redisTemplate.setKeySerializer(stringRedisSerializer);
		redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);

		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);

		redisTemplate.afterPropertiesSet();

		return redisTemplate;
	}
}
